package com.vzhv.myself.controller;

import com.vzhv.myself.mapper.JuanzhouMapper;
import com.vzhv.myself.vo.Juanzhou;
import com.vzhv.myself.vo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
public class JuanzhouController {
    @Autowired(required = false)
    JuanzhouMapper mapper;

    @RequestMapping("/juanzhou/insert")
    public int insert(Juanzhou juanzhou,
                      HttpSession session,
                      MultipartFile picFile) throws IOException {
        User u = (User) session.getAttribute("u");
        if (u == null){
            return 2;//未登录   请先登录
        }
        String fileName = picFile.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID()+suffix;//生成唯一的名字
        //生成路径
        String dirPath = "f:/upload1/";
        File dirFile = new File(dirPath);
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        String filePath = dirPath+fileName;
        picFile.transferTo(new File(filePath));

        juanzhou.setAuthor(u.getNick());
        juanzhou.setUrl("/"+fileName);
        juanzhou.setCreated(new Date());
        juanzhou.setUserId(u.getId());
        mapper.insert(juanzhou);
        return 1;//发布成功
    }

    @RequestMapping("/juanzhou/select")
    public List<Juanzhou> select(){
        return mapper.select();
    }

    @RequestMapping("/juanzhou/selectById")
    public Juanzhou select(int id){
        return mapper.selectById(id);
    }

}
